<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 * 
 * Official Website 
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */

class commonController extends appRain_Base_Core 
{
    public $name = 'Common';
    public $layout = 'blank';

     /**
     * Index page
     *
     * return NULL
     */ 
    public function indexAction()
    {
         echo ":(";
         exit;
    }
     /**
     * Dynamic image resize function 
     ----------------------------------------------------------------------------------------------
     * www.mysite/common/get_image/aW1nL2QuanBn/.5		: Resize 50% of orginal image
     * www.mysite/common/get_image/aW1nL2QuanBn/1		: Resize 100% of orginal image
     * www.mysite/common/get_image/aW1nL2QuanBn/100/fix : Resize to 100px of orginal image
     *
     *	@return byte-stream
     */
    public function get_imageAction( $file = NULL,  $size = NULL,$resize_flag = 'per' )
    {
        $this->layout='blank';
        $file =  base64_decode($file);
        $imagedata = GetImageSize($file);
        $width = $imagedata[0];
        $height = $imagedata[1];
        $imagetype = $imagedata[2];

        // Setting the resize parameters 
        list($width, $height) = getimagesize($file); 		
        if( $resize_flag == 'per')
        {
            $modwidth = $width * $size; 
            $modheight = $height * $size; 
        }
        else 
        {
            $modwidth = $size;
            $modheight = ( $height * $size ) / $width;
        }
        if($imagetype==2)
        {
            header('Content-type: image/jpeg'); 
            $tn = imagecreatetruecolor($modwidth, $modheight); 
            $image = imagecreatefromjpeg($file); 
            imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); 
            imagejpeg($tn, null, 100);
            imagedestroy($tn);
            imagedestroy($image);
        }
        elseif ($imagetype == 3)
        {
            header('Content-type: image/png'); 
            $tn = imagecreatetruecolor($modwidth, $modheight); 
            $image = imagecreatefrompng($file); 
            imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); 
            imagepng($tn);
            imagedestroy($tn);
            imagedestroy($image);
        }
        else
        {
            header('Content-type: image/gif'); 
            $tn = imagecreatetruecolor($modwidth, $modheight); 
            $image = imagecreatefromgif($file); 
            imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); 
            imagegif($tn, null, 100);
            imagedestroy($tn);
            imagedestroy($image);
        }
    }//function get_image()
    
    
    /**
     * Common function to delete. General userd of AJAX implementatio
     *
     *	@return NULL
     */
    public function delete_rowAction( $model = NULL, $id = NULL)
    {
        $this->layout = 'blank';
        $this->check_admin_login();	
        if( isset($model))
        {
            switch( $model )
            {
                case "delete_informationset_file" :
                                                    $info_dta = explode('|',$id);

                                                    $data = $this->informationSet()->findById($info_dta[1]);
                                                    if( $data[$info_dta[0]] != "" )
                                                    {
                                                        $path = $this->get_config('filemanager_path') . DS .  $data[$info_dta[0]];
                                                        if(file_exists($path)) unlink($path);
                                                    }
                                                   $this->informationSet()->Save(array("id"=>"{$info_dta[1]}",$info_dta[0]=>""));
                                                    exit;
                                                    break;
                case "Information":
                                                    $this->informationset()->Delete($id);
                                                    exit;
                                                    break;
                case "Category":
                                                    /*
                                                     * Delte all related data	
                                                     */
                                                    break;					
                default:
                                    break;
            }

            $rt = $this->$model->deleteById($id);
        }
        exit;
    }
    
   
    
    /**
     * A function to support multiple uploader addon
     *
     * @return null
     */
    public function general_uploadAction( $upload_path = "")
    {
        // Authentication
        $this->check_admin_login();	

        App::Load("Helper/Utility")->createFile('dd','a.txt');
        if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) 
        {
            header("HTTP/1.1 500 File Upload Error");
            
            if (isset($_FILES["Filedata"])) 
            {
                echo $_FILES["Filedata"]["error"];
            }
            exit(0);
        }
        else
        {
            if( $upload_path == "")
            {
                $upload_path = $this->get_config("filemanager_path") . "/";
                $upload_path = $this->basedir("/{$upload_path}");
            }
            else
            {
                $upload_path = base64_decode($upload_path);
            }

            $tmp_arr = App::Load("Helper/Utility")->upload($_FILES["Filedata"],"{$upload_path}"); 
            exit;
        }
    }

    /**
     *	Generate capacha
     *
     *	@return NULL
     */
    public function get_capachaAction($name = "image0",$options = NULL)
    {
        /* Decode the parematers */
        $name = base64_decode($name);		
        $arr = explode(',',base64_decode($options));
        $back_color = App::Load("Helper/Utility")->HexToRGB($arr[0] );
        $fore_color = App::Load("Helper/Utility")->HexToRGB($arr[1] );
        
        /* Set layout */
        $this->layout = 'blank';	
        
        /* Set image header */
        header("Content-type: image/png");

        /* Capacha text */
        $string =  rand(1000,9999);
        
        /* Register the session */
       App::Load("Module/Session")->write('capacha',array($name=>$string));

        /* Set image size */
        $im = imagecreate(100, 30);

        /* Set color */
        $bg = imagecolorallocate($im, $back_color["r"], $back_color["g"], $back_color["b"]);
        $orange = imagecolorallocate($im, $fore_color["r"], $fore_color["g"], $fore_color["b"]);
        
        /* Set out put */
        $px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
        imagestring($im, 3, $px, 9, $string, $orange);
        imagepng($im);
        imagedestroy($im);
        exit;
    }

    /**
    * Downlaod any server file 
    --------------------------------------------------
    * http://www.abc.com/common/downlaod/base64_encode(/home/public_html/myfile.pdf))
    --------------------------------------------------
    *
    * @parameter dwn_path string (Base 64 encoded file path)
    * @return NULL
    */
    public function downloadAction( $dwn_path = NULL)
    {
        // Decode the file
        $dwn_path = base64_decode($dwn_path);

        // Check the file if exists 
        if( @file_exists($dwn_path))
        {
            $tmp = @explode( "/", $dwn_path);
            $file_name = @end($tmp);
            $tmp = @explode( ".", $file_name);
            $ext = @end($tmp);

            @header("Content-type:{$ext}");
            @header("Content-Disposition: attachment; filename=\"{$file_name}\"");
            @readfile($dwn_path);
        } 
        else
        {
            // Die if no file exists
            die("Temporarily file is not available!  Please try after sometime.");
        }
    }

    public function default_cssAction()
    { 
        @header("Content-type:text/css");
    } 
  }
